package com.gipson.amc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dsbj.common.msg.DataPageMessage;
import com.dsbj.common.msg.ResponseMessage;
import com.gipson.amc.entity.*;
import com.gipson.amc.model.TreeNode;
import com.gipson.amc.service.basicdata.*;
import com.gipson.amc.utils.strprocess.CamelUnderlineProcess;
import com.sun.org.apache.regexp.internal.RE;
import io.micrometer.core.instrument.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/********
 * 资产资料
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    @Resource
    private RoleService roleService;
    @Resource
    private AuthorityService authorityService;
    @Resource
    private RoleAuthorityService roleAuthorityService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private ApplicationService applicationService;

    @RequestMapping("list")
    @RequiresPermissions("role.list")
    public String list(Model model){
        List<Application> applications = applicationService.getAllApp();
        model.addAttribute("applications",  applications);
        return "basicdata/role/list";
    }

    /***
     * 新增角色html
     * @param model
     * @return
     */
    @RequestMapping("addRole")
    @RequiresPermissions("role.add")
    public String addRole(Model model,String applicationId){
        List<TreeNode> treeNodes = getTreeMenuData2(applicationId);
        String json = JSONArray.toJSONString(treeNodes);
        Application application = applicationService.getById(applicationId);
        model.addAttribute("application",application);
        model.addAttribute("trees",json);
        return "basicdata/role/addRole";
    }
    /********
     * 编辑权限html
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("editMenuPeimission")
    @RequiresPermissions("role.menupeimission.edit")
    public String editMenuPeimission(Model model,String id){
        Role role = roleService.getById(id);
        List<String> roleAuths = new ArrayList<>();
        //根据rolecode查找权限
        List<RoleAuthority> roleAuthorityList = roleAuthorityService.getListByRoleId(id);
        for (RoleAuthority roleAuthority:roleAuthorityList){
            roleAuths.add(roleAuthority.getAuthorityId());
        }
        List<TreeNode> treeNodes = getTreeMenuData2(role.getApplicationId());
        String json = JSONArray.toJSONString(treeNodes);
        Application application = applicationService.getById(role.getApplicationId());
        model.addAttribute("application",application);
        model.addAttribute("trees",  json);
        model.addAttribute("role",  role);
        model.addAttribute("roleAuthorityJson",  StringUtils.join(roleAuths, ","));
        return "basicdata/role/editMenuPeimission";
    }

    /*******
     * 修改角色html
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("editRole")
    @RequiresPermissions("role.edit")
    public String editRole(Model model,String id){
        Role role = roleService.getById(id);
        Application application = applicationService.getById(role.getApplicationId());
        model.addAttribute("application",application);
        model.addAttribute("role",  role);
        return "basicdata/role/editRole";
    }

    @RequestMapping("ajaxLoadData")
    @RequiresPermissions("role.list")
    @ResponseBody
    public DataPageMessage ajaxLoadData(Role role ,PageByDataTable pageByDataTable){
        IPage<Role> page = roleService.selectPage(role,pageByDataTable);
        return DataPageMessage.ok(page.getRecords(), (int) page.getTotal(), (int) page.getTotal(),pageByDataTable.getSEcho(),"");
    }

    /******
     * 用户角色表
     * @return
     */
    @RequestMapping("ajaxLoadUserRoleData")
    @RequiresPermissions("role.user.edit")
    @ResponseBody
    public DataPageMessage ajaxLoadUserRoleData(UserRole userRole ,PageByDataTable pageByDataTable){
        IPage<UserRole> page = userRoleService.selectPageForUserRole(userRole,pageByDataTable);
        return DataPageMessage.ok(page.getRecords(), (int) page.getTotal(), (int) page.getTotal(),pageByDataTable.getSEcho(),"");
    }

    public List<TreeNode> getTreeMenuData2(String applicationId){
        List<TreeNode> treeList = new ArrayList<>();
        TreeNode rootTree = new TreeNode();
        rootTree.setId("0");
        rootTree.setPId("-1");
        rootTree.setIcon("/static/imgs/tree/1_open.png");
        rootTree.setName("全部");
        rootTree.setOpen(true);
        rootTree.setValue("0");
        treeList.add(rootTree);
        Map<Object,Object> map = new HashMap<>();
        map.put("type",Authority.TYPE_MENU);
        map.put("applicationId",applicationId);
        //获取所有菜单
        List<Authority> authorityList = authorityService.getAuthList(map);
        for(Authority authority:authorityList){
            TreeNode treeData = new TreeNode();
            treeData.setId(authority.getCode());
            if(StringUtils.isNotBlank(authority.getParentCode())){
                treeData.setPId(authority.getParentCode());
                treeData.setIcon("/static/imgs/tree/cate.png");
            }else{
                treeData.setPId("0");
                treeData.setIcon("/static/imgs/tree/cate.png");
            }
            treeData.setName(authority.getName());
            treeData.setOpen(false);
            treeData.setValue(authority.getId());
            treeList.add(treeData);
            //根据parent_code查询权限
            Map<Object,Object> map2 = new HashMap<>();
            map2.put("type",Authority.TYPE_PERMISSON);
            map2.put("parentCode",authority.getCode());
            map2.put("applicationId",applicationId);
            List<Authority> authorities = authorityService.getAuthList(map2);
            for(Authority authority1:authorities){
                TreeNode treeData2 = new TreeNode();
                treeData2.setId(authority1.getCode());
                treeData2.setPId(authority.getCode());
                treeData2.setOpen(false);
                treeData2.setIcon("/static/imgs/tree/3.png");
                treeData2.setName(authority1.getName()+"      "+authority1.getPermission());
                treeData2.setValue(authority1.getId());
                treeList.add(treeData2);
            }
        }
        return treeList;
    }

    /***
     * 保存角色并新增权限
     * @param role
     * @param nodes
     * @return
     */
    @RequestMapping("/saveRole")
    @RequiresPermissions("role.add")
    @ResponseBody
    public ResponseMessage saveRole(Role role,String nodes){
        return roleService.saveRole(role,nodes);
    }

    /***
     * 修改角色权限
     * @param id
     * @param nodes
     * @return
     */
    @RequestMapping("/saveRoleAuthority")
    @RequiresPermissions("role.menupeimission.edit")
    @ResponseBody
    public ResponseMessage saveRoleAuthority(String id,String nodes){
        return roleService.saveRoleAuthority(id,nodes);
    }

    @RequestMapping("/updateRole")
    @RequiresPermissions("role.edit")
    @ResponseBody
    public ResponseMessage updateRole(Role role){
        return roleService.updateRole(role);
    }

    /***
     * 单条删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteOne")
    @RequiresPermissions("role.delete")
    @ResponseBody
    public ResponseMessage deleteOne(String id){
        return roleService.deleteOne(id);
    }

    /**********
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping("/delBatch")
    @RequiresPermissions("role.delete")
    @ResponseBody
    public ResponseMessage delBatch(String ids){
        return roleService.delBatch(ids);
    }

    @RequestMapping("/listRoles")
    @ResponseBody
    public ResponseMessage listRoles(String username){
        Map<Object,Object> map = new HashMap<>();
        List<Role> userRoleList = null;
        if(StringUtils.isNotBlank(username)) {
            userRoleList = roleService.getRolesByUsername(username);
        }
        map.put("userRoleList",userRoleList);
        map.put("roleAll",roleService.list());
        return ResponseMessage.ok(map);
    }

    /*****
     * 分配用户
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("editUser")
    @RequiresPermissions("role.user.edit")
    public String editUser(Model model,String id){
        Role role = roleService.getById(id);
        Application application = applicationService.getById(role.getApplicationId());
        model.addAttribute("application",application);
        model.addAttribute("role",  role);
        return "basicdata/role/editUser";
    }


    /*****
     * 分配用户html
     * @return
     */
    @RequestMapping("selectUser")
    @RequiresPermissions("role.user.edit")
    public String selectUser(Model model,String roleId) {
        model.addAttribute("roleId",  roleId);
        return "basicdata/role/selectUser";
    }

    @RequestMapping("/saveUserRole")
    @RequiresPermissions("role.user.edit")
    @ResponseBody
    public ResponseMessage saveUserRole(String id,String userIds){
        return userRoleService.saveUserRole(id,userIds);
    }

    @RequestMapping("/deleteUserRole")
    @RequiresPermissions("role.user.edit")
    @ResponseBody
    public ResponseMessage deleteUserRole(String userId,String roleId){
        return userRoleService.deleteUserRole(userId,roleId);
    }

}
